package com.juguo.charginganimation.View.gallery;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.juguo.charginganimation.Base.Baseactivty;
import com.juguo.charginganimation.Bean.PhotoBean;
import com.juguo.charginganimation.Data.remote.RetrofitManager;
import com.juguo.charginganimation.MainApplication;
import com.juguo.charginganimation.R;
import com.juguo.charginganimation.utils.RxUtils;
import com.juguo.charginganimation.utils.ToastUtil;
import com.juguo.charginganimation.utils.UITools;
import com.juguo.charginganimation.repository.PixabayService;
import com.rosefinches.smiledialog.SmileDialog;
import com.rosefinches.smiledialog.SmileDialogBuilder;
import com.rosefinches.smiledialog.enums.SmileDialogType;

import java.io.File;

import io.reactivex.disposables.CompositeDisposable;
import io.supercharge.shimmerlayout.ShimmerLayout;
import pl.droidsonroids.gif.GifImageView;

public class GalleryDetail extends Baseactivty implements View.OnClickListener {

    private static final String TAG = "CIMO galleryDetail";
    private CompositeDisposable mDisposable = new CompositeDisposable();
    private ImageButton favorites_btn;
    private ImageButton favorites_btn_delet;
    /**
     * 数据源
     */
    private PhotoBean.Photos photos;
    static Activity activity;
    private ShimmerLayout shimmerLayout;
    private GifImageView photoView;
    private ImageButton imageButtonYydh;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery_detail);
        shimmerLayout = findViewById(R.id.shimerDetialIMG);
        photoView = findViewById(R.id.photoView);
        UITools.makeStatusBarTransparent(this);
        init();
        activity = this;
    }

    private void init() {
        //显示
        favorites_btn = findViewById(R.id.favorites_btn);
        favorites_btn.setOnClickListener(this::onClick);
        favorites_btn.setVisibility(View.VISIBLE);

        //隐藏藏
        favorites_btn_delet = findViewById(R.id.favorites_btn_delet);
        favorites_btn_delet.setOnClickListener(this::onClick);
        favorites_btn_delet.setVisibility(View.GONE);

        //应用动画
        imageButtonYydh = findViewById(R.id.imageButton_yydh);
        imageButtonYydh.setOnClickListener(this::onClick);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //shimmerLayout动画初始化
        shimmerLayout.setShimmerColor(0X55FFFFFF);
        shimmerLayout.setShimmerAngle(0);
        shimmerLayout.startShimmerAnimation();
        initGalleryDetailView();
    }


    @Override
    public void onClick(View v) {
        favorites_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                favorites_btn.setVisibility(View.GONE);
                favorites_btn_delet.setVisibility(View.VISIBLE);
                favoritesImage();
            }
        });
        favorites_btn_delet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                favorites_btn.setVisibility(View.VISIBLE);
                favorites_btn_delet.setVisibility(View.GONE);
                deleFavoritesImage();
            }
        });
        imageButtonYydh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ToastUtil.showToast(GalleryDetail.this, "电源接通22222888888888888888888");
                SharedPreferences sp = getApplication().getSharedPreferences("ImageYyds", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("coverImgUrl", photos.getCoverImgUrl()).apply();
                ToastUtil.showToast(MainApplication.getsInstance(), "应用成功！");
                //删除sp
                File file = new File("/data/data/" + getPackageName().toString() + "/shared_prefs", "ImageYydsSc.xml");
                if (file.exists()) {
                    file.delete();
                }
                File fileZzdh = new File("/data/data/" + getPackageName().toString() + "/shared_prefs", "ImageZzdh.xml");
                if (fileZzdh.exists()) {
                    fileZzdh.delete();
                }
                Intent intentYyds = new Intent(GalleryDetail.this, GalleryDetailYyds.class);
                intentYyds.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);  //只启动一个实例
                startActivity(intentYyds);
            }
        });

    }

    /**
     * 收藏图片
     */
    private void favoritesImage() {
        SharedPreferences sp = getApplication().getSharedPreferences("sp", Context.MODE_PRIVATE);
        String resId = sp.getString("resId", "");
        PixabayService service = RetrofitManager.getInstance()
                .getRetrofit()
                .create(PixabayService.class);
        mDisposable.add(service.favoritesImages(resId, 1)
                .compose(RxUtils.schedulersTransformer())
                .subscribe(favoritesBean -> {
                    Log.d(TAG, "favoritesBean: " + favoritesBean);
                    ToastUtil.showToast(getApplication(), "收藏成功！");
                }, throwable -> {
                    Log.d(TAG, "loadMore: " + throwable);
                }));
    }

    /**
     * 删除收藏
     */
    private void deleFavoritesImage() {
        SharedPreferences sp = getApplication().getSharedPreferences("sp", Context.MODE_PRIVATE);
        String resId = sp.getString("resId", null);
        PixabayService service = RetrofitManager.getInstance()
                .getRetrofit()
                .create(PixabayService.class);
        mDisposable.add(service.deleFavoritesImages(resId, 2)
                .compose(RxUtils.schedulersTransformer())
                .subscribe(favoritesBean -> {
                            Log.d(TAG, "favoritesBean: " + favoritesBean);
                            ToastUtil.showToast(getApplication(), "取消收藏！");
                            favorites_btn.setVisibility(View.VISIBLE);
                            favorites_btn_delet.setVisibility(View.GONE);
                        }
                        , throwable -> Log.d(TAG, "loadMore: " + throwable)));
    }

    /**
     * 初始化详情界面视图
     */
    private void initGalleryDetailView() {

        //从Parcelable获取图片数据
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            photos = bundle.getParcelable("CHECKED_PHOTO_ID");
        }
        //写入sp保存图片id
        SharedPreferences sp = getApplication().getSharedPreferences("sp", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("resId", photos.getId()).apply();
        //传入图片URL，Glide初始化
        Glide.with(getApplicationContext())
                //加载的URL
                .load(photos.getCoverImgUrl())
                //占位图片初始化
                .placeholder(R.drawable.ic_crop_original_black_24dp)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        if (shimmerLayout != null) {     //加载成功则停止动画
                            shimmerLayout.stopShimmerAnimation();
                        }
                        return false;
                    }
                })
                .into(photoView);    //装载图片
    }

    /**
     * 重写onBackPressed，用于配对进入动画
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        ActivityCompat.finishAfterTransition(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
